package com.zretc.support.service.serviceimpl;

import com.zretc.support.dao.JoincourseDao;
import com.zretc.support.dao.MessageDao;
import com.zretc.support.entity.Joincourse;
import com.zretc.support.entity.Message;
import com.zretc.support.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageDao md;
    @Autowired
    JoincourseDao jd;

    /**
     * 模糊+分页
     * @param keywords
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Page<Message> selectByPage(String keywords, Integer page, Integer limit) {
        Pageable pageable= PageRequest.of(page-1,limit);
        Page<Message> pd=md.selectByPage(keywords,pageable);
        return pd;
    }

    /**
     * 时间段查询
     * @param time1
     * @param time2
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Page<Message> selectByDate(Date time1,Date time2, Integer page, Integer limit) {
        Pageable pageable= PageRequest.of(page-1,limit);
        Page<Message> pd=md.selectByDate(time1,time2,pageable);
        return pd;
    }

    /**
     * 增加消息
     * @param message
     * @return
     */
    @Override
    public int addMessage(Message message) {
        Message message1=md.save(message);
        if (message1!=null){
            return 1;
        }
        return 0;
    }

    /**
     * 修改消息
     * @param message
     * @return
     */
    @Override
    public int updMessage(Message message) {
        md.save(message);
        return 1;
    }

    /**
     * 根据id删除消息
     * @param messageId
     * @return
     */
    @Override
    public int delMesById(Integer messageId) {
        try{
            md.deleteById(messageId);
        }catch (Exception e){
            return 0;
        }
        return 1;
    }

    @Override
    public Page<Message> selMesByUserId(String userId, int page, int size) {
        Pageable pageable = PageRequest.of(page-1, size);

        List<Joincourse> joincourseList = jd.findByUser_UserId(userId);
        List<Long> courseIdList = new ArrayList<>();

        for (int i = 0; i < joincourseList.size(); i++) {
            courseIdList.add(joincourseList.get(i).getCourse().getCourseId());
        }

        Page<Message> messages = md.selectByCourseId(courseIdList,pageable);
        return messages;
    }
}
